package com.goldcontrol.cloudweb.service;

import com.goldcontrol.cloudweb.common.Constants;
import com.goldcontrol.cloudweb.mapper.ScheduledMapper;
import com.goldcontrol.cloudweb.model.JobEntity;
import com.goldcontrol.cloudweb.quartz.SchedulerManager;
import com.goldcontrol.cloudweb.quartz.job.DynamicJob;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ScheduledService {

    private static Logger logger = Logger.getLogger(ScheduledService.class);

    @Autowired
    private SchedulerManager schedulerManager;

    @Autowired
    ScheduledMapper scheduledMapper;

    public List<JobEntity> getActiveJobs(Integer jobStatus){
        Map<String,Object> param = new HashMap<>();
        param.put("jobStatus",jobStatus);
        return scheduledMapper.selectJobByFields(param);
    }

    public void addProjectJob(JobEntity jobEntity){
        scheduledMapper.insert(jobEntity);
    }

    /**
     * 添加开机任务
     * @param jobEntity
     * @param   0 关机  1 开机
     */
    public void addQuartzJob(JobEntity jobEntity){
        try {
            String jobName = "JOB_NAME_"+jobEntity.getProjectId()+"_"+jobEntity.getState();
            jobEntity.setJobName(jobName);
            jobEntity.setGroupName(Constants.JOB_GROUP_NAME);

            if(StringUtils.isNotBlank(jobEntity.getCronTime())){
                schedulerManager.addJob(jobEntity, DynamicJob.class);
            }
        } catch (Exception e) {
            logger.error("addJob error {}",e);
        }
    }


    /**
     * 更新加开机任务
     * @param jobEntity
     */
    public void updateQuartzJob(JobEntity jobEntity){
        try {
            String jobName = "JOB_NAME_"+jobEntity.getProjectId()+"_"+jobEntity.getState();
            jobEntity.setJobName(jobName);
            jobEntity.setGroupName(Constants.JOB_GROUP_NAME);
            schedulerManager.updateJob(jobEntity);
        } catch (Exception e) {
            logger.error("updateJob error {}",e);
        }
    }

    public List<JobEntity> getJob(int projectId){
        Map<String,Object> param = new HashMap<>();
        param.put("projectId",projectId);
        return scheduledMapper.selectJobByFields(param);
    }

    public void removeQuartzJob(int projectId,int state){
        String jobName = "JOB_NAME_"+projectId+"_"+state;
        JobEntity jobEntity = new JobEntity();
        jobEntity.setJobName(jobName);
        jobEntity.setGroupName(Constants.JOB_GROUP_NAME);
        schedulerManager.removeJob(jobEntity);
    }

    public boolean checkIfExists(int projectId,int state){
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("projectId",projectId);
        param.put("state",state);
        List<JobEntity> list = scheduledMapper.selectJobByFields(param);
        if(list == null || list.size() == 0){
            return true;
        }
        return false;
    }

    public void updateProjectSingleJobStatus(JobEntity jobEntity) {
        JobEntity job = scheduledMapper.selectJob(jobEntity.getProjectId(),jobEntity.getState());
        if(job == null){
            scheduledMapper.insert(jobEntity);
        }else{
            scheduledMapper.update(jobEntity);
        }
        Map<String,Object> param = new HashMap<>();
        param.put("projectId",jobEntity.getProjectId());
        param.put("jobStatus",jobEntity.getJobStatus());
        scheduledMapper.updateProjectStatus(param);
    }

    public void updateProjectAllJobStatus(int projectId,int onff) {
        Map<String,Object> param = new HashMap<>();
        param.put("projectId",projectId);
        JobEntity onJob = scheduledMapper.selectJob(projectId,1);
        JobEntity offJob = scheduledMapper.selectJob(projectId,0);
        if(onJob == null){
            scheduledMapper.insert(getJobEntity(projectId,1));
        }
        if(offJob == null){
            scheduledMapper.insert(getJobEntity(projectId,0));
        }
        param.put("projectId",projectId);
        param.put("jobStatus",onff);
        scheduledMapper.updateProjectStatus(param);
    }

    private JobEntity getJobEntity(int projectId,int onoff){
        JobEntity jobEntity = new JobEntity();
        jobEntity.setProjectId(projectId);
        jobEntity.setJobStatus(onoff);
        return jobEntity;
    }

    public boolean checkJobIfExists(JobEntity jobEntity){
        return checkIfExists(jobEntity.getProjectId(),jobEntity.getState());
    }

    public String getCronTime(String time) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new Date());
        String newDate = date + " " + time;
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(sdf1.parse(newDate));
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int min = calendar.get(Calendar.MINUTE);
        return "0 "+min+" "+hour+" * * ? *";
    }

}
